package org.example.user.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.user.domain.User;
import org.example.user.service.UserService;
import org.example.user.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public Result getUser(@RequestBody User user){
        String code = (String) redisTemplate.opsForValue().get("code_"+user.getUid());
        Long aLong = redisTemplate.opsForValue().increment("user_" + user.getUsername(), 1);
        if(aLong>3){
            redisTemplate.expire("user_" + user.getUsername(),1, TimeUnit.MINUTES);
            return Result.fail("登录失败次数过多");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User userDB = userService.getOne(wrapper);
        if (userDB != null){
            if(userDB.getPassword().equals(user.getPassword())){
                if(code.equals(user.getCode())){
                    redisTemplate.delete("user_" + user.getUsername());
                    String token = JwtUtils.createToken(BeanUtil.beanToMap(userDB));
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("token",token);
                    map.put("nickName",userDB.getNickName());
                    map.put("uid",userDB.getUid());
                    return Result.success("登录成功",map);
                }
            }
        }
        /**
         * 重试失败3次后封禁15分钟
         */

        return Result.fail("用户名、密码或验证码不正确");
    }
    @RequestMapping("/getCodeUrl")
    public void getCodeUrl(HttpServletResponse response,String uid) throws IOException {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());
        redisTemplate.opsForValue().set("code_"+uid,captcha.getCode(),5,TimeUnit.MINUTES);
    }
    @GetMapping("/users")
    @ApiOperation(value = "users接口",httpMethod = "GET",notes = "用来创建一个新的对象")
    public User getUsers(){
        return new User();
    }

    @RequestMapping("{userId}")
    public User getUser(@PathVariable("userId") Integer userId) {
        return userService.getById(userId);
    }
}
